import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:signage/app/constants/template_constants.dart';
import 'package:signage/app/data/models/board_element.dart';
import 'package:signage/app/utils/toast_utils.dart';
import 'package:signage/l10n/l10n.dart';
import 'package:signage/widgets/custom_appbar.dart';

import '../../../data/models/template_model.dart';
import '../../../../widgets/template_list_item.dart';
import '../controllers/template_controller.dart';

class TemplateView extends GetView<TemplateController> {
  final String? source;
  const TemplateView({
    super.key,
    this.source,
  });
  @override
  Widget build(BuildContext context) {
    return Obx(() => DefaultTabController(
          length: 5,
          child: Scaffold(
              backgroundColor: Color(0XFFF3F4F6),
              body: Stack(
                children: [
                  Image.asset('assets/images/title_bar_bg.png',
                      width: Get.width),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      CustomAppBar(
                        title: AppLocalizations.of(context)!.translate('choose_template'),
                        showBackButton: source?.isNotEmpty == true,
                        rightButtons: [
                          // GestureDetector(
                          //   onTap: () {
                          //     ToastUtils.show(AppLocalizations.of(context)!.translate('coming_soon'));
                          //   },
                          //   child: Image.asset('assets/images/Frame@2x (2).png',
                          //       width: 21.w),
                          // ),
                          // 20.horizontalSpace,
                          // GestureDetector(
                          //   onTap: () {
                          //     ToastUtils.show(AppLocalizations.of(context)!.translate('coming_soon'));
                          //   },
                          //   child: Image.asset('assets/images/Frame@2x (3).png',
                          //       width: 24.w),
                          // ),
                          // 16.horizontalSpace,
                        ],
                      ),
                      Row(
                        children: [
                          Expanded(
                            child: TabBar(
                              controller: controller.tabController,
                              padding: EdgeInsets.only(
                                  left: 16.w), // Add padding zero
                              tabAlignment: TabAlignment.start,
                              labelPadding: EdgeInsets.symmetric(
                                  horizontal: 10, vertical: 0), // 调整tab之间的间距
                              isScrollable: true,
                              indicator: null,
                              indicatorColor: Colors.transparent,
                              dividerHeight: 0,
                              tabs: [
                                _buildTab(AppLocalizations.of(context)!.translate('all'), 0),
                                _buildTab(AppLocalizations.of(context)!.translate('simple'), 1),
                                _buildTab(AppLocalizations.of(context)!.translate('party'), 2),
                                _buildTab(AppLocalizations.of(context)!.translate('agenda'), 3),
                                _buildTab(AppLocalizations.of(context)!.translate('my_templates'), 4),
                              ],
                            ),
                          ),
                          Padding(
                            padding: EdgeInsets.only(bottom: 5.h),
                            child: Row(
                              children: [
                                Container(
                                  width: 0.5.w,
                                  height: 18.h,
                                  decoration: BoxDecoration(
                                    color: Color(0XFF999999),
                                    borderRadius: BorderRadius.circular(2),
                                  ),
                                ),
                                12.horizontalSpace,
                                // 新增下拉选择框
                                PopupMenuButton<String>(
                                  elevation: 0,
                                  padding: EdgeInsets.zero,
                                  constraints: BoxConstraints(
                                    minWidth: Get.width,
                                    maxHeight: 600.h,
                                  ),
                                  color: Colors.white,
                                  onSelected: (String newValue) {
                                    // 处理选择的尺寸
                                    controller.selectedSize.value = newValue;
                                    controller.loadTemplates();
                                  },
                                  position: PopupMenuPosition.under,
                                  itemBuilder: (BuildContext context) {
                                    return <String>[
                                      AppLocalizations.of(context)!.translate('all'),
                                      ...TemplateConstants
                                          .deviceScreenSize.entries
                                          .map((e) => "${e.value} | ${e.key}")
                                    ].map<PopupMenuItem<String>>(
                                        (String value) {
                                      return PopupMenuItem<String>(
                                        value: value,
                                        child: Row(
                                          // 设置宽度为拉满
                                          mainAxisAlignment:
                                              MainAxisAlignment.spaceBetween,
                                          children: [
                                            Text(value,
                                                style: TextStyle(
                                                  fontSize: 14.sp,
                                                  color: Color(0XFF333333),
                                                )),
                                            if (value ==
                                                controller.selectedSize.value)
                                              Image.asset(
                                                  'assets/images/Group 1321318579@2x.png',
                                                  width: 22.w,
                                                  height: 22.h),
                                          ],
                                        ),
                                      );
                                    }).toList();
                                  },
                                  offset: Offset(0, 12.h),
                                  child: Row(
                                    children: [
                                      Text(
                                          controller.selectedSize.value == AppLocalizations.of(context)!.translate('all')
                                              ? AppLocalizations.of(context)!.translate('size')
                                              : controller.selectedSize.value,
                                          style: TextStyle(
                                            fontSize: 14,
                                            fontWeight: FontWeight.w400,
                                            letterSpacing: 0,
                                            color: Color(0XFF333333),
                                          )),
                                      8.horizontalSpace,
                                      Image.asset(
                                          'assets/images/Vector@2x (1).png',
                                          width: 12.w),
                                    ],
                                  ), // 显示提示文本
                                ),
                                16.horizontalSpace,
                              ],
                            ),
                          )
                        ],
                      ),
                      7.verticalSpace,
                      Expanded(
                        child: Container(
                          decoration: BoxDecoration(
                            color: Color(0XFFF3F4F6),
                            borderRadius: BorderRadius.only(
                              topLeft: Radius.circular(18),
                              topRight: Radius.circular(18),
                            ),
                          ),
                          child: TabBarView(
                            controller: controller.tabController,
                            children: [
                              _buildTemplateList(controller.allTemplates),
                              _buildTemplateList(controller.simpleTemplates),
                              _buildTemplateList(controller.partyTemplates),
                              _buildTemplateList(controller.agendaTemplates),
                              _buildTemplateList(controller.myTemplates),
                            ],
                          ),
                        ),
                      )
                    ],
                  ),
                  Positioned(
                    bottom: 20.h,
                    right: 20.w,
                    child: FloatingActionButton(
                      backgroundColor: Color(0XFFFCCF01),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(100),
                      ),
                      onPressed: () {
                        controller.clickNewTemplate();
                      },
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Icon(
                            Icons.add,
                            size: 18.w,
                            color: Colors.black,
                          ),
                          2.verticalSpace,
                          Text(
                            AppLocalizations.of(context)!.translate('create_new'),
                            style: TextStyle(
                              fontSize: 12.sp,
                              fontWeight: FontWeight.w400,
                              letterSpacing: 0,
                              color: Color(0XFF333333),
                            ),
                          ),
                        ],
                      ),
                    ),
                  )
                ],
              )),
        ));
  }

  Widget _buildTab(String label, int index) {
    return Column(
      children: [
        Text(
          label,
          style: TextStyle(
            fontSize: 16.sp,
            height: 26.h / 16.sp,
            color: Color(0XFF333333),
          ),
        ),
        controller.currentTab.value == index
            ? Image.asset(
                'assets/images/Vector@2x.png',
                width: 13.w,
                height: 5.h,
              )
            : SizedBox(height: 5.h)
      ],
    );
  }

  Widget _buildTemplateList(RxList<TemplateModel> templates) {
    return templates.isEmpty
        ? Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const Icon(
                  Icons.description_outlined,
                  size: 80,
                  color: Colors.black26,
                ),
                const SizedBox(height: 16),
                Text(
                  AppLocalizations.of(Get.context!)!.translate('no_templates'),
                  style: TextStyle(
                    fontSize: 16,
                    color: Colors.black54,
                  ),
                ),
                const SizedBox(height: 8),
              ],
            ),
          )
        : ListView.separated(
            padding: const EdgeInsets.all(16),
            itemCount: templates.length,
            separatorBuilder: (context, index) => const SizedBox(height: 16),
            itemBuilder: (context, index) {
              final template = templates[index];
              return TemplateListItem(
                template: template,
                onTap: () => controller.handleTemplateSelection(template),
                onDelete: () => controller.deleteTemplate(template),
                onPin: () => controller.togglePinTemplate(template),
                onCopy: () => controller.copyTemplate(template),
                onEdit: () => controller.editTemplate(template),
                onRename: (newName) {
                  if (newName.trim().isNotEmpty) {
                    controller.renameTemplate(template, newName);
                  }
                },
              );
            },
          );
  }
}
